Page({
  data: {
    cellArr: [],
  },
  onLoad: function () {
    this.startGame()
  },
  startGame() {
    this.setData({
      cellArr: Array.from(Array(4)).map(() => Array(4).fill(0)),
    })
    this.fillOneEmptyCell()
    this.fillOneEmptyCell()
  },
  fillOneEmptyCell() {
    const emptyCells = this.findEmptyCells()
    if (emptyCells.length > 0) {
      const [row, col] = emptyCells[this.random(emptyCells.length)]
      this.data.cellArr[row][col] = this.getRandomValue()
      this.setData({ cellArr: this.data.cellArr })
    }
  },
  getRandomValue() {
    return Math.random() < 0.9 ? 2 : 4
  },
  random(max) {
    return Math.floor(Math.random() * max)
  },
  findEmptyCells() {
    const emptyCells = []
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (this.data.cellArr[i][j] === 0) {
          emptyCells.push([i, j])
        }
      }
    }
    return emptyCells
  },
  touchStartX: 0,
  touchStartY: 0,
  touchEndX: 0,
  touchEndY: 0,
  touchStart(ev) {
    const touch = ev.touches[0]
    this.touchStartX = touch.clientX
    this.touchStartY = touch.clientY
  },
  touchMove(ev) {
    const touch = ev.touches[0]
    this.touchEndX = touch.clientX
    this.touchEndY = touch.clientY
  },
  touchEnd() {
    const disX = this.touchEndX - this.touchStartX
    const absDisX = Math.abs(disX)
    const disY = this.touchEndY - this.touchStartY
    const absDisY = Math.abs(disY)

    if (Math.max(absDisX, absDisY) > 10) {
      if (absDisX > absDisY) {
        this.move(disX > 0 ? 'right' : 'left')
      } else {
        this.move(disY > 0 ? 'down' : 'up')
      }
    }
  },
  move(direction) {
    console.log(direction);
  },
})